package cn.study.synchronizedTest;

import java.util.Date;
/**
 * @Author     ：跟大佳一起学架构
 * @Description：Synchronized加锁范围
 */
public class SynchronizedLockScope {
    public static Object obj = new Object();

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            new SynchronizedLockScope().test1();
        }).start();
        new Thread(() -> {
            new SynchronizedLockScope().test2();
        }).start();

        new Thread(() -> {
            new SynchronizedLockScope().test3();
        }).start();
        new Thread(() -> {
            new SynchronizedLockScope().test4();
        }).start();

        Thread.sleep(4000);
    }

    public void test3(){
//        synchronized (SynchronizedLockScope.class) {
//        synchronized (this) {
        synchronized (obj) {
            System.out.println("test1 " + new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("test1 " + new Date() + " " + Thread.currentThread().getName() + " end...");
        }
    }
    public void test4(){
//            synchronized (SynchronizedLockScope.class) {
//            synchronized (this) {
            synchronized (obj) {
                System.out.println("test2 " + new Date() + " " + Thread.currentThread().getName() + " begin...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("test2 " + new Date() + " " + Thread.currentThread().getName() + " end...");
        }
    }



    public synchronized void test1(){
        System.out.println("test1 " + new Date() + " " + Thread.currentThread().getName() + " begin...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test1 " + new Date() + " " + Thread.currentThread().getName() + " end...");
    }

    public synchronized void test2(){
        System.out.println("test1 " + new Date() + " " + Thread.currentThread().getName() + " begin...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test1 " + new Date() + " " + Thread.currentThread().getName() + " end...");
    }


}